package com.example.mq.lock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;
/*
@description:
@ClassName DefaultDistributeLock
@author chen
@create 2025-08-14 18:04
@Version 1.0
*/
@Slf4j
@Component
public class DefaultDistributeLock implements DistributeLock
{
    private static ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public boolean accept(String lockKey, Consumer<String> consumer)
    {
        Objects.requireNonNull(lockKey);
        Objects.requireNonNull(consumer);

        boolean flag = reentrantLock.tryLock();
        try
        {
            if (log.isInfoEnabled())
            {
                log.info("get lock:[{}],[{}]", lockKey, flag);
            }
            if (!flag)
            {
                return false;
            }
            consumer.accept(lockKey);
        }
        finally
        {
            if (flag)
            {
                reentrantLock.unlock();
            }
        }
        return true;
    }

    @Override
    public void accept(String lockKey, Consumer<String> consumer, Function<String, ? extends RuntimeException> lockFailException)
    {
        Objects.requireNonNull(lockKey);
        Objects.requireNonNull(consumer);
        Objects.requireNonNull(lockFailException);

        boolean flag = this.accept(lockKey, consumer);
        if (!flag)
        {
            throw lockFailException.apply(lockKey);
        }
    }
}
